<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth {

	private $CI;

	function __construct()
	{
		$this->CI = & get_instance();
	}
	
	public function Register($_email, $_password, $_name)
	{
		$array = $this->CreateHash($_password);

		$data = array(
	   		'Email' => $_email,
	   		'Password' => $array["hash"],
	   		'Name' => $_name,
	   		'Salt' => $array["salt"],
	   		'Privileges_Id' => 1
		);

			$dbres = $this->CI->db->insert('Users', $data);
			if($dbres == FALSE)
				return FALSE;

			$this->CI->db->from('Privileges')->where('Id', 1);
			$query = $this->CI->db->get();
			$row = $query->first_row();

			$this->Change_Session($_email, $_name, $row->Id, $row->Role, TRUE);
			return TRUE;
		


	}

	public function Login($_email, $_password)
	{
		$this->CI->db->from('Users')->join('Privileges', 'Privileges.Id = Users.Privileges_Id')->where('Email', $_email);
		$query = $this->CI->db->get();

		if($query->num_rows() > 0)
		{
			$row = $query->first_row();
			$encrypted_password = $this->Encode($_password, $row->Salt);
			if($encrypted_password == $row->Password)
			{
				$this->Change_Session($row->Email, $row->Name, $row->Id, $row->Role, TRUE);
				return TRUE;
			}
			return FALSE;
		}
		else
		{
			return FALSE;
		}
	}

	public function Logout()
	{
		$this->CI->session->sess_destroy();
	}

	public function Auth()
	{
		$user = $this->CI->session->userdata('logged_in');
		if($user == TRUE)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}

	private function CreateHash($_password)
	{
		$salt = sha1(md5($_password));
		$hash = $this->Encode($_password, $salt);

		$array = array();
		$array["salt"] = $salt;
		$array["hash"] = $hash;
		return $array;
	}

	private function Encode($_password, $_salt)
	{
		// 123 chars
		return md5($_password.$_salt);
	}

	private function Change_Session($_email, $_name, $_privilegeid, $_privilegerole, $_loggedin)
	{
		$newdata = array(
			'email' => $_email,
			'name' => $_name,
			'privilege_id' => $_privilegeid,
			'privilege_role' => $_privilegerole,
			'logged_in' => $_loggedin
		);
		$this->CI->session->set_userdata($newdata);
	}
}

?>